package com.i2works.smartluolong.api.controller.company;

import com.alibaba.fastjson.JSONObject;
import com.i2works.smartluolong.api.controller.common.CommonItemController;
import com.i2works.smartluolong.utils.base.CompanyConstant;
import com.i2works.smartluolong.utils.base.CompanyStatusEnum;
import com.i2works.smartluolong.utils.base.FlowItemTypeEnum;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.common.BaseUtils;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.entity.company.CompanyApplyDO;
import com.i2works.smartluolong.web.entity.company.CompanyApplyImagesDO;
import com.i2works.smartluolong.web.entity.company.CompanyApplyImagesQuery;
import com.i2works.smartluolong.web.entity.company.CompanyApplyQuery;
import com.i2works.smartluolong.web.entity.flow.FlowProcessDO;
import com.i2works.smartluolong.web.service.company.ICompanyApplyImagesService;
import com.i2works.smartluolong.web.service.company.ICompanyApplyMemberService;
import com.i2works.smartluolong.web.service.company.ICompanyApplyService;
import com.i2works.smartluolong.web.service.flow.IFlowProcessService;
import com.i2works.smartluolong.web.service.flow.IFlowService;
import com.i2works.smartluolong.web.service.flow.IFlowTemplateService;
import com.xiaoleilu.hutool.collection.CollUtil;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 工商申请 - 控制器
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/3/15 9:48
 */
@RestController
@RequestMapping("/companyApply")
public class CompanyApplyController extends CommonItemController {

    private final ICompanyApplyService companyApplyService;
    private final ICompanyApplyImagesService companyApplyImagesService;

    public CompanyApplyController(IFlowTemplateService flowTemplateService, IFlowService flowService, IFlowProcessService flowProcessService, ICompanyApplyService companyApplyService, ICompanyApplyImagesService companyApplyImagesService) {
        super(flowTemplateService, flowService, flowProcessService);
        this.companyApplyService = companyApplyService;
        this.companyApplyImagesService = companyApplyImagesService;
    }


    /**
     * 查看工商申请 - 页面
     */
    @GetMapping(value = "/view/{applyId:\\d+}")
    public Result queryPage(@PathVariable Integer applyId) {
        //参数判断
        if (applyId == null) {
            return R.error(MsgEnum.ATTRS_EMPTY.getMsg());
        }
        return getApplyDetail(applyId);
    }


    /**
     * 公司基本信息(回显)
     */
    @GetMapping("/base/{applyId:\\d+}")
    public Result base(@PathVariable Integer applyId) {
        JSONObject jsonObject = new JSONObject();
        //参数判断
        if (applyId == null) {
            return R.error(MsgEnum.ATTRS_EMPTY.getMsg());
        }
        try {
            //查询申请ID是不是当前用户的
            CompanyApplyQuery companyApplyQuery = new CompanyApplyQuery();
            companyApplyQuery.setUserId(getUserId());
            companyApplyQuery.setId(applyId);
            CompanyApplyDO companyApply = companyApplyService.query(companyApplyQuery);
            if (null == companyApply) {
                return R.error(MsgEnum.FIND_ERROR.getMsg());
            }
            //基本资料
            jsonObject.put("companyApply", companyApply);
            //备选字号
            String[] brandOptionalList = companyApply.getCompanyBrandOptional().split(",");
            jsonObject.put("brandOptionalList", brandOptionalList);
            //申请图片
            CompanyApplyImagesQuery imagesQuery = new CompanyApplyImagesQuery();
            imagesQuery.setApplyId(companyApply.getId());

            Integer queryCount = companyApplyImagesService.queryCount(imagesQuery);
            List<CompanyApplyImagesDO> applyImagesList = null;
            if (queryCount > 0) {
                applyImagesList = companyApplyImagesService.queryList(imagesQuery);
            }
            jsonObject.put("companyApplyImagesList", applyImagesList);
        } catch (ServiceException e) {
            logger.error("公司基本信息(回显)异常：" + e.getMessage());
            return R.error(MsgEnum.SYSTEM_ERROR.getMsg());
        }
        return R.success(jsonObject);
    }


    /**
     * 新增基本信息
     */
    @PostMapping("/save")
    public Result save(@ModelAttribute CompanyApplyDO companyApply) {
        try {
            //用户信息
            companyApply.setUserId(getUserId());
            //创建人信息
            companyApply.setUpdateName(getUserName());
            //公司名称补充完整
            companyApply.setCompanyName(companyApply.getRegion() + companyApply.getCompanyBrand() + companyApply.getIndustry() + CompanyConstant.base.COMPANY_TYPE);
            //地址补充完整
            //companyApply.setRegion(CompanyConstant.base.REGION_PREFIX);
            companyApply.setCompanyAddress("洛阳市洛龙区"+companyApply.getCompanyAddress());
            //备用字号格式化
            String companyBrandOptional = BaseUtils.listToStr(companyApply.getCompanyBrandOptionalList(), ",");
            companyApply.setCompanyBrandOptional(companyBrandOptional);
            //行业
            companyApply.setCompanyType(CompanyConstant.base.COMPANY_TYPE);
            //状态
            companyApply.setApplyStatus(CompanyStatusEnum.STATUS_0.getKey());
            //保存
            companyApplyService.saveOrUpdate(companyApply);
            return R.success(companyApply);
        } catch (Exception e) {
            logger.error("新增公司基本信息异常：" + e.getMessage());
            return R.error(MsgEnum.SAVE_ERROR.getMsg());
        }
    }


    /**
     * 工商申请提交成功提示
     */
    @GetMapping("/success/{applyId:\\d+}")
    public Result success(@PathVariable("applyId") Integer applyId) {
        JSONObject jsonObject = new JSONObject();
        //查询申请ID是不是当前用户的
        CompanyApplyQuery companyApplyQuery = new CompanyApplyQuery();
        companyApplyQuery.setUserId(getUserId());
        companyApplyQuery.setId(applyId);
        companyApplyQuery.setApplyStatus(CompanyStatusEnum.STATUS_10.getKey());
        try {
            CompanyApplyDO companyApply = companyApplyService.query(companyApplyQuery);
   /*         if (null == companyApply) {
                return R.error(MsgEnum.SYSTEM_ERROR.getMsg());
            }*/
//            else {
//                //更新状态
//                companyApply.setApplyStatus(CompanyStatusEnum.STATUS_10.getKey());
//                companyApplyService.update(companyApply);
//            }
            jsonObject.put("company", companyApply);
            jsonObject.put("companyStatus", getApplyStatus(companyApply.getApplyStatus()));
        } catch (ServiceException e) {
            logger.error("申请成功异常：" + e.getMessage());
        }
        return R.success(jsonObject);
    }


    /**
     * 工商申请审核日志
     */
    @GetMapping("/auditInfo/{applyId:\\d+}")
    public Result auditInfo(@PathVariable("applyId") Integer applyId) {
        try {
            CompanyApplyQuery companyApplyQuery = new CompanyApplyQuery();
            companyApplyQuery.setId(applyId);
            Integer count = companyApplyService.queryCount(companyApplyQuery);
            if (count > 0) {
                List<FlowProcessDO> flowProcess = queryFlowProcess(applyId, FlowItemTypeEnum.COMPANY_APPLY.getKey());
                return R.success(flowProcess, flowProcess.size());
            } else {
                return R.error(MsgEnum.FIND_ERROR.getMsg());
            }
        } catch (ServiceException e) {
            logger.error("工商申请审核日志异常：" + e.getMessage());
            return R.error("工商申请审核日志异常：" + e.getMessage());
        }
    }


    /**
     * 获取申请状态
     */
    private String getApplyStatus(Integer key) {
        CompanyStatusEnum[] enums = CompanyStatusEnum.values();
        for (CompanyStatusEnum applyStatusEnum : enums) {
            if (applyStatusEnum.getKey().equals(key)) {
                return applyStatusEnum.getText();
            }
        }
        return CompanyStatusEnum.STATUS_0.getText();
    }


    /**
     * 工商申请详情
     */
    private Result getApplyDetail(Integer applyId) {
        Map<String, Object> resultMap;
        try {
            resultMap = companyApplyService.getApplyDetail(applyId);
            if (CollUtil.isEmpty(resultMap)) {
                return R.error(MsgEnum.FIND_ERROR.getMsg());
            }
            //查询流程
            resultMap.put("flowProcessList", queryFlowProcess(applyId, FlowItemTypeEnum.COMPANY_APPLY.getKey()));
        } catch (Exception e) {
            logger.error("", e);
            return R.error(MsgEnum.SYSTEM_ERROR.getMsg());
        }
        return R.success(resultMap);
    }



}
